package com.ruoyi.api.worker;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.RefundModel;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pay.WxPayXiaoChengXuConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.ProfileUtil;
import com.ruoyi.system.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/worker/order")
@Api(tags = "社工端订单详情接口")
public class ApiWorkerOrderController {

    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaWorkerService workerService;

    @Autowired
    private IJiajiaUserService userService;



    @Autowired
    private IJiajiaMessageService messageService;


    @Autowired
    private IJiajiaUserMoneyChangeService moneyChangeService;

    @Autowired
    private IJiajiaOrderTimeService orderTimeService;

    @Autowired
    private IJiajiaItemService itemService;


    @Autowired
    private WxPayXiaoChengXuConfig xiaoChengXuConfig;


    @ApiOperation(value = "社工订单详情接口")
    @PostMapping("/orderDetails")
    public AjaxResult orderDetail(@RequestParam @ApiParam(value = "订单ID") Long id) {
        JiajiaOrder order = orderService.selectJiajiaOrderById(id);
        return AjaxResult.success(order);
    }

    @ApiOperation("社工订单列表")
    @PostMapping("/orderList")
    public AjaxResult orderList(@RequestParam @ApiParam(value = "0 全部订单 1 待接单 2进行中 6已完成 7取消/售后") Integer status,
                                @RequestParam Integer pageNo,
                                @RequestParam Integer pageSize) {

        JiajiaWorker worker = workerService.selectJiajiaWorkerById(TokenUtil.getUid());
        if (worker.getCodeAuth().intValue() != 1){
            return AjaxResult.error("请先进行身份认证");
        }

        JiajiaOrder order = new JiajiaOrder();
        order.getParams().put("js2Type", status);
        order.setWid(worker.getId());
        PageHelper.startPage(pageNo, pageSize, "addtime desc");
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        for (JiajiaOrder model : orderList) {
//            List<JiajiaOrderTime> orderTimeList = orderTimeService.selectList(model.getOrderSn());
            String daoJiShi = "";
            JiajiaOrderTime jiajiaOrderTime = new JiajiaOrderTime();
            jiajiaOrderTime.setOrderSn(model.getOrderSn());
            List<JiajiaOrderTime> orderTimeList = orderTimeService.selectJiajiaOrderTimeList(jiajiaOrderTime);
            if (ObjectUtil.isNotEmpty(orderTimeList)) {//获取预约时间最早的一个时间
                model.setOrderTimeList(orderTimeList);
                JiajiaOrderTime orderTime = orderTimeList.get(0);
                String dayTime = orderTime.getDay()+" "+orderTime.getStartTime()+":00";
                Date startTime = DateUtils.parseDate(dayTime);
                daoJiShi = DateUtils.getDatePoor(startTime, new Date());
            }
            if (model.getStatus().intValue() == 1) {
                model.getParams().put("statusDes", "待确认");
                model.getParams().put("daoJiShi", daoJiShi);
            } else if (model.getStatus().intValue() == 6) {
                model.getParams().put("statusDes", "已完成");
            } else if (model.getStatus().intValue() == 7) {
                model.getParams().put("statusDes", "已取消");
            } else if (model.getStatus().intValue() == 8) {
                model.getParams().put("statusDes", "拒绝接单");
            } else {
                model.getParams().put("statusDes", "进行中");
                model.getParams().put("daoJiShi", daoJiShi);
            }

            model.getParams().put("juLi", TokenUtil.getLuLi(model.getLat(), model.getLng()));
        }
        return AjaxResult.success(orderList);
    }

    @ApiOperation("改变订单状态")
    @PostMapping("/userChangeOrderStatus")
    @Transactional
    public AjaxResult apiOrderStatus(@RequestParam Long orderId,Integer status) {
            if(TokenUtil.isLogin()){
                //订单
                JiajiaOrder order = orderService.selectJiajiaOrderById(orderId);

                workerService.apiOrderStatus(order,status);
                return AjaxResult.success();
            }else {
                return AjaxResult.notLogin();
            }

    }
    @ApiOperation("改变订单状态")
    @PostMapping("/changeOrderStatus")
    @Transactional
    public AjaxResult orderStatus(@RequestParam Long orderId,
                                @RequestParam @ApiParam(value = "2确认接单 3出发 4到达 5开始服务 6结束服务 8拒绝服务") Integer status) {

        JiajiaWorker workerSource = workerService.selectJiajiaWorkerById(TokenUtil.getUid());
        if (workerSource == null)return AjaxResult.notLogin();
        JiajiaWorker worker = new JiajiaWorker();
        worker.setId(workerSource.getId());
        JiajiaOrder order = orderService.selectJiajiaOrderById(orderId);
        if (order == null)return AjaxResult.refreshAgain();
        String content ="";

        JiajiaItem item = itemService.selectJiajiaItemById(order.getIid());
        if (item == null)return AjaxResult.refreshAgain();

        if (status == 2){
            //确认接单
            order.setJietime(new Date());
            content = "社工已接单";
        }
        if (status == 3){
            //出发
            order.setChufatime(new Date());
            content = "社工已出发";
        }
        if (status == 4){
            //到达 ---判断社工位置
//            if (TokenUtil.getLuLiNum(order.getLat(),order.getLng()).floatValue() > 3){
//                return AjaxResult.error("未到指定地点，请重新检查定位");
//            }
            order.setDaodatime(new Date());
            content = "社工已到达";
        }
        if (status == 5){
            //开始服务 --判断社工位置
//            if (TokenUtil.getLuLiNum(order.getLat(),order.getLng()).floatValue() > 3){
//                return AjaxResult.error("未到指定地点，请重新检查定位");
//            }
            order.setStarTime(new Date());
            content = "社工开始服务";
        }
        if (status == 6){//社工结束服务
            order.setEndtime(new Date());


            content = "社工结束服务";
        }
        if (status == 8){
            //拒绝接单
            //社工拒绝次数加1
            worker.setUnNum(worker.getUnNum().intValue() + 1);

            order.setCancelStatus(1);
            order.setCanceltime(new Date());

            //退款给客户
            if(order.getPayType().intValue() == 0){
                JiajiaUser user = userService.selectJiajiaUserById(order.getUid());
                if (user != null){
                    JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
                    moneyChange.setChangeBefore(user.getMoney());

                    user.setMoney(new BigDecimal(user.getMoney().floatValue() + order.getRealPrice().floatValue()));
                    userService.updateJiajiaUser(user);

                    moneyChange.setChangeAfter(user.getMoney());
                    moneyChange.setChangeMoney(order.getRealPrice());
                    moneyChange.setDes("社工拒绝接单，返还金额");
                    moneyChange.setType("订单取消");
                    moneyChange.setOtherId(order.getOrderSn());
                    moneyChange.setUid(order.getUid());
                    moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);
                }
            }else if (order.getPayType().intValue() == 3 && order.getPayStatus().intValue() == 1 ){
                String tuiMoney = String.valueOf((order.getRealPrice().multiply(new BigDecimal("100"))).intValue());
                if (ProfileUtil.getActiveProfile().equals(ProfileUtil.PROFILE_DEV)){
                    tuiMoney = "1";
                }

                //这里是走小程序退款
                Map<String, String> params = RefundModel.builder()
                        .appid(xiaoChengXuConfig.getAppid())
                        .mch_id(xiaoChengXuConfig.getMachid())
                        .nonce_str(WxPayKit.generateStr())
                        .out_trade_no(order.getOrderSn())
                        .out_refund_no(order.getOrderSn())
                        .total_fee(tuiMoney)
                        .refund_fee(tuiMoney)
                        .notify_url(xiaoChengXuConfig.getNotifyUrl()+"/api/paynotify/refundNotify")
                        .build()
                        .createSign(xiaoChengXuConfig.getMckKey(), SignType.MD5);
                InputStream certIs = null;
                try {
                    ClassPathResource classPathResource = new ClassPathResource(xiaoChengXuConfig.getKeyPath());
                    certIs = classPathResource.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String refundResult = WxPayApi.orderRefundByProtocol(false, params, certIs, xiaoChengXuConfig.getMachid(), "");
                Map<String,String> map = WxPayKit.xmlToMap(refundResult);
                String returnCode = map.get("return_code");
                String resultCode = map.get("result_code");
                if (!resultCode.equals("SUCCESS") || !returnCode.equals("SUCCESS")){
                    throw new RuntimeException("退款失败");
                }
            }
            content = "社工拒绝接单";
        }


        worker.setLat(StringUtils.isEmpty(TokenUtil.getLat())?null:TokenUtil.getLat());
        worker.setLng(StringUtils.isEmpty(TokenUtil.getLng())?null:TokenUtil.getLng());
        workerService.updateJiajiaWorker(worker);

        order.setStatus(status);
        orderService.updateJiajiaOrder(order);

        //创建通知
        JiajiaMessage message = new JiajiaMessage();
        message.setType(2);
        message.setTitle("订单状态改变");
        message.setContent(content);
        message.setUid(order.getUid());
        messageService.insertJiajiaMessage(message);

        return AjaxResult.success();
    }




}
